﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WMM.Tapioca.Instance;
using WMM.Tapioca.Taxonomy;
using WMM.Tapioca.Utilities;
using System.Xml;

namespace WMM.Tapioca.Formula.Filters
{
    /// <summary>
    /// The entity identifier filter can be used to match facts based upon characteristics of 
    /// the entity identification scheme and/or the entity identification value.
    /// </summary>
    public class IdentifierFilter : Filter
    {
        private string test;

        /// <returns> XPath expression. </returns>
        public string Test
        {
            get { return test; }
            set { test = value; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public IdentifierFilter(Linkbase.Resource resource)
            : base(resource)
        {
            string expression = (string)resource.ResourceXElement.Attribute("test") ?? string.Empty;
            expression = expression.TrimEnd().TrimStart();
            expression = Regex.Replace(expression, @"\s+", " ");
            test = expression;
        }


        public override List<FactItem> EvaluateFilter(VariableSet variableSet, List<FactItem> itemsToFilter, DTS dts)
        {
            this.dts = dts;

            List<FactItem> itemListTemp = new List<FactItem>();

            foreach (FactItem itemToFilter in itemsToFilter)
            {
                Context context = itemToFilter.ContextRef;
                XmlNode identifier = context.EntityElement.Element(xbrli + "identifier").ToXmlNode();

                string result = EvaluateXPathExpression(Test, identifier);

                if (Complement ? !result.Equals("true") : result.Equals("true"))
                {
                    itemListTemp.Add(itemToFilter);
                }
            }

            return itemListTemp;
        }
    }
}
